package cn.myspringboot.system.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.myspringboot.base.mapper.BaseMapper;
import cn.myspringboot.base.service.impl.BaseServiceImpl;
import cn.myspringboot.system.mapper.EmployeeMapper;
import cn.myspringboot.system.mapper.LogininfoMapper;
import cn.myspringboot.system.service.EmployeeService;
import cn.myspringboot.user.domain.Employee;
import cn.myspringboot.user.domain.Logininfo;
import cn.myspringboot.user.domain.vo.EmployeeVo;
import cn.myspringboot.user.query.EmployeeQuery;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    @Transactional
    public PageInfo<Employee> selectEmployeePage(EmployeeQuery query) {
        PageHelper.startPage(query.getPage(), query.getSize());
        List<Employee> employees = employeeMapper.selectEmployeePage(query);
        PageInfo<Employee> pageInfo = new PageInfo<>(employees);
        return pageInfo;
    }

    @Override
    @Transactional
    public void add(EmployeeVo employeeVo) {
        Employee employee = EmployeeVo.of(employeeVo);
        String salt = RandomUtil.randomString(32);
        employee.setSalt(salt);
        String s = SecureUtil.md5(salt + "123456");
        employee.setPassword(s);
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee, logininfo);
        logininfo.setType(0);
        logininfo.setDisable(1);
        logininfoMapper.add(logininfo);
        employee.setLogininfoId(logininfo.getId());
        employeeMapper.add(employee);
        Long id = employee.getId();
        employeeMapper.addByRolesAndEmployeeId(id,employeeVo.getRoles());
    }

    @Override
    @Transactional
    public void update(EmployeeVo employeeVo) {
        Employee byId = employeeMapper.getById(employeeVo.getId());
        BeanUtils.copyProperties(employeeVo, byId);
        employeeMapper.update(byId);
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employeeVo, logininfo);
        logininfo.setId(byId.getLogininfoId());
        logininfoMapper.update(logininfo);
        employeeMapper.delByRolesAndEmployeeId(employeeVo.getId());
        employeeMapper.addByRolesAndEmployeeId(employeeVo.getId(),employeeVo.getRoles());
    }
}
